package munci.old.use;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Wraps common checked exception throwing methods with runtime exceptions
 * @author Giles Burgess
 */
public class Try {

	public static Object get(Field field, Object object) {
		try {
			return field.get(object);
		} catch (Exception e) {
			throw except(e);
		}
	}
	
	public static void set(Field field, Object obj, Object value) {
		try {
			field.set(obj, value);
		} catch (Exception e) {
			throw except(e);
		}
	}
	
    public static Object invoke(Method method, Object obj, Object... args) {
    	try {
    		try {
    			return method.invoke(obj, args);
    		} catch (InvocationTargetException e) {
    			throw e.getCause();
    		}
		} catch (Throwable e) {
			throw except(e);
		}
    }
    
    public static String toString(Object obj) {
    	return obj == null? "null" : obj.toString();
    }
    
    public static Method getMethod(Class<?> type, String name, Class<?>... parameterTypes) {
    	try {
			return type.getMethod(name, parameterTypes);
		} catch (Exception e) {
			throw except(e);
		}
    }
    
    public static RuntimeException except(String str) {
    	return new RuntimeException(str);
    }
    
    public static RuntimeException except(String str, Throwable ex) {
    	if (ex != null && ex.getMessage() == null) return except(str, ex.getCause());
    	
    	if (ex instanceof RuntimeException && ex.getMessage() == null) {
    		RuntimeException e = new RuntimeException(str, ex.getCause());
    		e.setStackTrace(ex.getStackTrace());
    		return e;
    	}
    	return new RuntimeException(str, ex);
    }
    
    public static RuntimeException except(Throwable ex) {
    	if (ex != null && ex.getMessage() == null) return except(ex.getCause());
    	
    	try {
    		throw ex;
    	} catch (RuntimeException e) {
    		return e;
    	} catch (Throwable e) {
    		return new RuntimeException(e);
    	}
    }

}
